from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4RouteInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4RouteInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class RouteInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()

	def isYieldsDefined(self, iRoute):
		objRouteInfo = gc.getRouteInfo(iRoute)
		
		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objRouteInfo.getYieldChange(iI) != 0):
				return true
		return false

	def isTechMovementChangesDefined(self, iRoute):
		objRouteInfo = gc.getRouteInfo(iRoute)

		for iI in range(gc.getNumTechInfos()):
			if(objRouteInfo.getTechMovementChange(iI) != 0):
				return true
		return false

	def printRoute(self, iRoute):
		objRouteInfo = gc.getRouteInfo(iRoute)

		szText = ""
		
		szText = appendString(szText,"		<RouteInfo>")
		
		szText = appendString(szText,"			<Type>%s</Type>" %(objRouteInfo.getType()))


		szText = appendString(szText,"			<Description>%s</Description>" %(objRouteInfo.getTextKey()))

		szText = appendString(szText,"			<iValue>%s</iValue>" %(objRouteInfo.getValue()))
		szText = appendString(szText,"			<iMovement>%s</iMovement>" %(objRouteInfo.getMovementCost()))
		szText = appendString(szText,"			<iFlatMovement>%s</iFlatMovement>" %(objRouteInfo.getFlatMovementCost()))

		if(objRouteInfo.getPrereqBonus() != -1):
			szText = appendString(szText,"			<BonusType>%s</BonusType>" %(gc.getBonusInfo(objRouteInfo.getPrereqBonus()).getType()))
		else:
			szText = appendString(szText,"			<BonusType>NONE</BonusType>")
		
		if(self.isYieldsDefined(iRoute)):
			szText = appendString(szText,"			<Yields>")
			for iI in range(YieldTypes.NUM_YIELD_TYPES):
				szText = appendString(szText,"				<iYield>%s</iYield>" %(objRouteInfo.getYieldChange(iI)))
			szText = appendString(szText,"			</Yields>")
		else:
			szText = appendString(szText,"			<Yields/>")
			

		if(self.isTechMovementChangesDefined(iRoute)):
			szText = appendString(szText,"			<TechMovementChanges>")

			for iI in range(gc.getNumTechInfos()):
				if(objRouteInfo.getTechMovementChange(iI) != 0):
					szText = appendString(szText,"				<TechMovementChange>")
					szText = appendString(szText,"					<PrereqTech>%s</PrereqTech>" %(gc.getTechInfo(iI).getType()))
					szText = appendString(szText,"					<iMovementChange>%s</iMovementChange>" %(objRouteInfo.getTechMovementChange(iI)))
					szText = appendString(szText,"				</TechMovementChange>")
			szText = appendString(szText,"			</TechMovementChanges>")
		else:
			szText = appendString(szText,"			<TechMovementChanges/>")			
		
		szText = appendString(szText,"			<Button>%s</Button>" %(objRouteInfo.getButton()))

		szText = appendString(szText,"		</RouteInfo>")
			
		return szText

						
	def printRoutes(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Misc" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4RouteInfos.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Route Infos -->")
		szText = appendString(szText,"<Civ4RouteInfos xmlns=\"x-schema:CIV4MiscSchema.xml\">")
		szText = appendString(szText,"	<RouteInfos>")
		szText = appendString(szText,"		<fZBias>%s</fZBias>" %(gc.getRouteZBias()))
				
		for iRoute in range(gc.getNumRouteInfos()):

			if(gc.getRouteInfo(iRoute).isDeleted()):
				continue

			szText = appendString(szText,self.printRoute(iRoute))
			
						
		szText = appendString(szText,"	</RouteInfos>")
		szText = appendString(szText,"</Civ4RouteInfos>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\Misc")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\Misc\CIV4RouteInfos.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
			
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

